﻿using System;
using System.Linq;
using System.Xml.Linq;

namespace CodeCounsel.SharePoint.RibbonDesigner.Model
{
    public abstract class ChildCollectionDomainElement<TCollection,TItem>
        : NamedDomainElement
        where TCollection : DomainElementContainer<TItem>
        where TItem: DomainElement
    {
        public TCollection Items
        {
            get { return Children.OfType<TCollection>().FirstOrDefault(); }
        }

        protected ChildCollectionDomainElement(
            XElement dataModel, DomainModelSource source)
            : base(dataModel, source)
        {
        }

        protected ChildCollectionDomainElement()
        {
        }

        protected override bool HandleRemove(
            XElement element)
        {
            bool handled = false;
            if ((handled = base.HandleRemove(element)) == false)
            {
                TCollection items = Items;
                if (items != null)
                {
                    TItem domainElement = items.Children.Where(c => c.DataModel == element).FirstOrDefault() as TItem;
                    if (domainElement != null)
                    {
                        items.Children.Remove(domainElement);
                        RaiseChildDomainElementRemoved((TItem)domainElement);
                        handled = true;
                    }
                }
            }
            return handled;
        }

        protected virtual void RaiseChildDomainElementRemoved(TItem item)
        {
        }
    }
}
